<?php

class Weather
{
    private $api_nowurl = 'https://api.thinkpage.cn/v3/weather/now.json?key=btwgk4nwdfd3m01d&location=suzhou&language=zh-Hans&unit=c';
    private $api_afturl = 'https://api.thinkpage.cn/v3/weather/daily.json?key=btwgk4nwdfd3m01d&location=suzhou&language=zh-Hans&unit=c&start=0&days=5';
    function __construct(){
        $this->CI = & get_instance();
        $this->CI->load->model('weather_model');
    }

// 实时天气 type = 0
    function weather_now(){
        
        $now_json = $this->get_weather_json(0);
        $now_data = json_decode($now_json,TRUE);

        $now = $now_data['results'][0]['now'];

        return $now;

    }
// 2 天天气 type = 1 daliy_arr : 0 =>today  1=>next day
    public function weather_daliy(){
        $daliy_json = $this->get_weather_json(1);
        $daliy_data = json_decode($daliy_json,TRUE);

        $daliy_arr = $daliy_data['results'][0]['daily'];

        return $daliy_arr;

    }

    private function get_weather_json($type){
        $now = time();
        $now_json = '';
        $now_data = $this->CI->weather_model->get(array('type'=>$type));
        $url = $this->api_nowurl;
        if($type === 1){
            $url = $this->api_afturl;
        }
        
        if(empty($now_data) || ($now-$now_data['upd_time'])>$now_data['expire_time'] ){
            
            $now_json = file_get_contents($url);
            
            $now = array(
                'data' => $now_json,
                'type' => $type,
                'upd_time' => $now,
                'expire_time' => 3600
            );
            if(empty($now_data)){
                $this->CI->weather_model->add($now);
            }else{
                $this->CI->weather_model->upd($now,array('type'=>0));  
            }
        }else{
            $now_json = $now_data['data'];
        }

        return $now_json;
    }

}